const fs = require('fs');
const path = require('path');

const projectDir = process.env.INIT_CWD || path.resolve('../../', __dirname);
const vscodeDir = path.resolve(projectDir, '.vscode');
if (!fs.existsSync(vscodeDir)) {
  fs.mkdirSync(vscodeDir);
}

const settingsPath = path.resolve(vscodeDir, 'settings.json');
let settings = {
  'eslint.validate': [
    'javascript',
    'javascriptreact',
    {
      language: 'typescript',
      autoFix: true,
    },
    {
      language: 'typescriptreact',
      autoFix: true,
    },
  ],
  'eslint.autoFixOnSave': true,
};

if (fs.existsSync(settingsPath)) {
  const content = fs.readFileSync(settingsPath);
  try {
    const cur = JSON.parse(content);
    settings = Object.assign({}, cur, settings);
  } catch (err) {
    console.error(err);
  }
}

// 增加换行符，以免自动格式化后的提交有变更
fs.writeFileSync(settingsPath, `${JSON.stringify(settings, null, 2)}\n`);
